<template>
  <div class="adminDoc">
    <a-layout>
      <a-layout-content
          :style="{ background: '#fff', padding: '24px', margin: 0, minHeight: '280px' }"
      >
        <a-row :gutter="24">
          <a-col :span="8">
            <p>
              <a-form layout="inline" :model="param">
                <a-form-item>
                  <a-button  @click="handleQuery()" shape="round">
                    <redo-outlined />
                  </a-button>
                </a-form-item>
                <a-form-item>
                  <a-button  @click="add()" shape="round">
                    <file-add-outlined />
                    扩充文档
                  </a-button>
                </a-form-item>
              </a-form>
            </p>

            <a-table
                v-if="level1.length > 0"
                :data-source="level1"
                :columns="columns"
                :row-key="record => record.id"
                :loading="loading"
                :pagination="false"
                size="small"
                :defaultExpandAllRows="true"
            >

              <template #name="{ text,record }">
                {{record.sort}} {{ text }}
              </template>

              <template v-slot:action="{ text, record }">
                <a-space size="small">
                  <a-button  @click="edit(record)" size="small" shape="round">
                    <edit-outlined />
                    编辑
                  </a-button>
                  <a-popconfirm
                      title="确定要删除这个文档吗？"
                      ok-text="是的"
                      cancel-text="不是"
                      @confirm="handleDelete(record.id)"
                  >
                    <a-button  size="small" shape="round">
                      <delete-outlined />
                      删除
                    </a-button>
                  </a-popconfirm>
                </a-space>
              </template>
            </a-table>
          </a-col>
          <a-col :span="16">
            <p>
              <a-form>
                <a-form-item>
                  <a-button  @click="handleSave()" shape="round">
                    <save-outlined />
                    保存
                  </a-button>
                </a-form-item>
              </a-form>
            </p>
            <a-form :model="doc" layout="vertical">

              <a-form-item>
                <a-input v-model:value="doc.name" placeholder="名称" />
              </a-form-item>

              <a-form-item>
                <a-tree-select
                    v-model:value="doc.parent"
                    style="width: 100%"
                    :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                    :tree-data="treeSelectData"
                    placeholder="请选择父文档"
                    tree-default-expand-all
                    :replaceFields="{title: 'name', key: 'id', value: 'id'}"
                >
                </a-tree-select>
              </a-form-item>
              <a-form-item>
                <a-input v-model:value="doc.sort" placeholder="顺序"/>
              </a-form-item>
              <a-form-item>
                <a-button  @click="handlePreviewContent()" shape="round">
                  <EyeOutlined /> 内容预览
                </a-button>
              </a-form-item>
              <a-form-item>
                <div id="content"></div>
              </a-form-item>
            </a-form>
          </a-col>
        </a-row>

        <a-drawer width="900" placement="right" :closable="false" :visible="drawerVisible" @close="onDrawerClose">
          <div class="wangeditor" :innerHTML="previewHtml"></div>
        </a-drawer>

      </a-layout-content>
    </a-layout>
  </div>
<!--  <a-modal-->
<!--      title="文档表单"-->
<!--      v-model:visible="modalVisible"-->
<!--      :confirm-loading="modalLoading"-->
<!--      @ok="handleModalOk"-->
<!--  >-->
<!--    -->
<!--  </a-modal>-->
</template>

<script lang="ts">
import { defineComponent, onMounted,ref, createVNode } from 'vue';
import axios from 'axios';
import { message, Modal } from "ant-design-vue";
import {Tool} from "@/util/tool";
import { useRoute } from 'vue-router';
import E from 'wangeditor';
import i18next from "i18next";


export default defineComponent({
  name:'AdminDoc',
  setup() {

    const route = useRoute();
    const param = ref();
    param.value={};
    const docs = ref();
    const loading = ref(false);
    const treeSelectData = ref();
    treeSelectData.value = [];

    const columns = [

      {
        title: '名称',
        dataIndex: 'name',
        slots: { customRender: 'name' }
      },
      {
        title: '',
        key: 'action',
        slots: {customRender: 'action'}
      }
    ];

    /**
     * 一级文档树，children属性就是二级文档
     * [{
     *   id: "",
     *   name: "",
     *   children: [{
     *     id: "",
     *     name: "",
     *   }]
     * }]
     */
    const level1 = ref(); // 一级文档树，children属性就是二级文档
    level1.value = [];
    /**
     * 数据查询,前后端分页同步
     **/
    const handleQuery = () => {
      loading.value = true;
      // 如果不清空现有数据，则编辑保存重新加载数据后，再点编辑，则列表显示的还是编辑前的数据
      level1.value = [];
      axios.get("/doc/all/"+ route.query.ebookId).then((response) =>{

        loading.value=false;
        const data = response.data;
        if (data.success){
          docs.value= data.content;
          console.log("原始数组：", docs.value);

          level1.value = [];
          level1.value = Tool.array2Tree(docs.value, 0);
          console.log("树形结构：", level1);
          // 父文档下拉框初始化，相当于点击新增,如果不加“|| []”那么当一个电子书内没有文档时，新增文档时父文档什么都没有（'无'也没有）
          treeSelectData.value = Tool.copy(level1.value) || [];
          // 为选择树添加一个"无"
          treeSelectData.value.unshift({id: 0, name: '无'});
        }else {
          message.error(data.message);
        }
      });
    };

    /**
     * 内容查询
     **/
    const handleQueryContent = () => {
      axios.get("/doc/find-content/" + doc.value.id).then((response) => {
        const data = response.data;
        if (data.success) {
          editor.txt.html(data.content)
        } else {
          message.error(data.message);
        }
      });
    };

    const setDisable = (treeSelectData: any, id: any) => {
      // console.log(treeSelectData, id);
      // 遍历数组，即遍历某一层节点
      for (let i = 0; i < treeSelectData.length; i++) {
        const node = treeSelectData[i];
        if (node.id === id) {
          // 如果当前节点就是目标节点
          console.log("disabled", node);
          // 将目标节点设置为disabled
          node.disabled = true;

          // 遍历所有子节点，将所有子节点全部都加上disabled
          const children = node.children;
          if (Tool.isNotEmpty(children)) {
            for (let j = 0; j < children.length; j++) {
              setDisable(children, children[j].id)
            }
          }
        } else {
          // 如果当前节点不是目标节点，则到其子节点再找找看。
          const children = node.children;
          if (Tool.isNotEmpty(children)) {
            setDisable(children, id);
          }
        }
      }
    };

    const ids :Array<string> = [];
    /**
     * 查找整根树枝
     */
    const getDeleteIds = (treeSelectData: any, id: any) => {
      // console.log(treeSelectData, id);
      // 遍历数组，即遍历某一层节点
      for (let i = 0; i < treeSelectData.length; i++) {
        const node = treeSelectData[i];
        if (node.id === id) {
          // 如果当前节点就是目标节点
          console.log("delete", node);
          // 将目标ID放入结果集ids
          // node.disabled = true;
          ids.push(id);


          // 遍历所有子节点
          const children = node.children;
          if (Tool.isNotEmpty(children)) {
            for (let j = 0; j < children.length; j++) {
              getDeleteIds(children, children[j].id)
            }
          }
        } else {
          // 如果当前节点不是目标节点，则到其子节点再找找看。
          const children = node.children;
          if (Tool.isNotEmpty(children)) {
            getDeleteIds(children, id);
          }
        }
      }
    };

    // -------表单--------

    const doc= ref();
    doc.value = {
      ebookId:route.query.ebookId
    };
    // console.log("doc的主键id:"+route.query.ebookId)
    const modalVisible = ref(false);
    const modalLoading = ref(false);
    const editor = new E('#content');
    editor.config.zIndex = 0;
    // 引入 i18next 插件,默认情况 wangeditor 是不提供多语言功能的,想要使用多语言功能仅仅是安装了 i18next 还不够，
    // 还需要把 i18next 接入到 wangeditor 当中
    editor.i18next = i18next


    const handleSave = () => {
      // 点击ok先显示loading效果
      modalLoading.value = true;
      doc.value.content = editor.txt.html();
      axios.post("/doc/save", doc.value).then((response) => {

        modalLoading.value = false;

        // 当post请求发送以后，值返回时执行以下操作
        const data = response.data;
        if (data.success){ // data = CommonResp,所以有success属性
          // 如果保存成功，取消loading效果，关闭对话框

          // modalVisible.value = false;
          message.success("保存成功!");
          // 关闭对话框后重新加载列表
          handleQuery()
        }else {
          message.error(data.message);
        }

      });
    };

    // 编辑功能，点击编辑按钮时触发的事件
    const edit = (record:any) => {
      // 清空富文本框
      editor.txt.html("");
      // 显示模态框
      modalVisible.value = true;
      doc.value = Tool.copy(record);
      handleQueryContent();
      // 不能选择当前节点及其所有子孙节点，作为父节点，会使树断开
      treeSelectData.value = Tool.copy(level1.value);
      setDisable(treeSelectData.value, record.id);

      // 为选择树添加一个"无",unshift是自带的方法，作用是往数组前面添加一个值，push是往后面添加
      treeSelectData.value.unshift({id: 0, name: '无'});

    };

    // 新增功能，点击新增按钮时触发的事件
    const add = () => {
      // 清空富文本框
      editor.txt.html("");

      modalVisible.value = true;
      doc.value = {
        ebookId:route.query.ebookId
      };
      treeSelectData.value = Tool.copy(level1.value) || [];

      // 为选择树添加一个"无"
      treeSelectData.value.unshift({id: 0, name: '无'});

    };

    // 删除功能，点击删除按钮时触发的事件
    const handleDelete = (id:number) =>{
      getDeleteIds(level1.value, id);
      axios.delete("/doc/delete/"+ ids.join(",")).then((response) => {

        // 当delete请求发送以后，值返回时执行以下操作
        const data = response.data;
        if (data.success){ // data = CommonResp,所以有success属性
          // 如果删除成功，直接重新加载列表
          handleQuery()
        }
      });
    };

    /**
     * 根据name查询电子书信息
     */
    // const handleQueryByName = (params: any) => {
    //   loading.value = true;
    //   docs.value = [];
    //   axios.get("/doc/search", {
    //     params: {
    //       page: params.page,
    //       size: params.size,
    //       name: searchDoc.value.name
    //     }
    //   }).then((response) => {
    //
    //     loading.value = false;
    //     const data = response.data;
    //     if (data.success) {
    //       docs.value = data.content.list;
    //       // 重置分页按钮
    //       pagination.value.current = params.page;
    //       pagination.value.total = data.content.total;
    //     } else {
    //       message.error(data.message);
    //     }
    //
    //   })
    // };

        // ----------------富文本预览--------------
    const drawerVisible = ref(false);
    const previewHtml = ref();
    const handlePreviewContent = () => {
      const html = editor.txt.html();
      previewHtml.value = html;
      drawerVisible.value = true;
    };
    const onDrawerClose = () => {
      drawerVisible.value = false;
    };

    onMounted(() => {
      handleQuery();

      editor.create();
    });

    onMounted(()=>{
      handleQuery();
      editor.create();
    })

    return{
      // 表格用到的返回参数
      // docs,
      level1,
      columns,
      loading,


      // 新增和编辑
      edit,
      add,

      // 表单用到的返回参数
      doc,
      modalVisible,
      modalLoading,
      handleSave,

      handleDelete,

      //搜索功能用到的返回参数
      handleQuery,
      param,

      treeSelectData,

      // 富文本预览用到的返回参数
      drawerVisible,
      previewHtml,
      handlePreviewContent,
      onDrawerClose,
    }
  },
});
</script>
<style scoped>
.adminDoc{
  text-align: center;
  margin: 15px 200px 10px;
}
.adminEbookHeader{
  margin: 15px 310px 10px;

}
</style>